package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

/**
 *
 *
 * @date 2024-06-29 03:21:25
 * @author zhangxiaofanfan
 */
public class HotCode071 {
    public static void main(String[] args) {
        HotCode071 hotCode = new HotCode071();
        String s = "3[a2[c]]";
        System.out.println(hotCode.decodeString(s));
    }

    public String decodeString(String s) {
        if (s == null || s.isEmpty()) {
            throw new RuntimeException("输入字符串不满足要求, 请重新参数");
        }
        Deque<String> inStack = new ArrayDeque<>();
        Stack<String> strStack = new Stack<>();
        Stack<String> numStack = new Stack<>();
        String left = "[", right = "]";
        for (Character curChar : s.toCharArray()) {
            if (!curChar.toString().equals(right)) {
                inStack.addLast(curChar.toString());
            } else {
                while (!inStack.getLast().equals(left)) {
                    strStack.push(inStack.removeLast());
                }
                inStack.removeLast();
                while (!inStack.isEmpty() && inStack.getLast().length() == 1 && Character.isDigit(inStack.getLast().charAt(0))) {
                    numStack.push(inStack.removeLast());
                }
                StringBuilder template = new StringBuilder();
                StringBuilder newString = new StringBuilder();
                int count = 0;
                while (!strStack.isEmpty()) template.append(strStack.pop());
                while (!numStack.isEmpty()) count = count * 10 + Integer.parseInt(numStack.pop());
                newString.append(String.valueOf(template).repeat(Math.max(0, count)));
                inStack.addLast(newString.toString());
            }
        }
        StringBuilder result = new StringBuilder();
        while (!inStack.isEmpty()) result.append(inStack.removeFirst());
        return result.toString();
    }

}
